﻿using OpenTK.Mathematics;

namespace TrinityEngine
{
    public enum ClearFlags
    {
        Skybox = 0,
        SolidColor = 1,
        DepthOnly = 2,
        DontClear = 3
    }

    public enum Projection
    {
        Perspective = 0,
        Orthographic = 1
    }

    public enum FovAxis
    {
        Horizontal = 0,
        Vertical = 1
    }

    public class Camera
    {
        public static Camera main;

        public Transform transform = new Transform();

        public ClearFlags clearFlags { get; set; } = ClearFlags.SolidColor;

        public Color background { get; set; } = Color.Black;

        public Projection projectionType { get; set; } = Projection.Orthographic;

        public float size { get; set; } = 5f;

        public FovAxis fovAxis { get; set; } = FovAxis.Vertical;

        public float fieldOfView { get; set; } = 60;

        public float near { get; set; } = 0.3f;

        public float far { get; set; } = 1000f;

        public Rect viewportRect { get; set; } = new Rect(0, 0, 1, 1);

        public Matrix4 worldToCameraMatrix
        {
            get => GetViewMatrix() * GetProjectionMatrix();
        }

        public Camera()
        {
            transform.position = new Vector3(0f, 0f, -10f);
        }

        private Matrix4 GetProjectionMatrix()
        {
            Matrix4 projection;
            if (projectionType == Projection.Perspective)
            {
                Matrix4.CreatePerspectiveFieldOfView(fieldOfView, Screen.aspect, near, far, out projection);
            }
            else
            {
                Matrix4.CreateOrthographic(size * 2f * Screen.aspect, size * 2f, near, far, out projection);
            }

            return projection;
        }

        private Matrix4 GetViewMatrix()
        {
            return Matrix4.CreateFromQuaternion(transform.rotation) *
                Matrix4.CreateTranslation(-transform.position.x, -transform.position.y, transform.position.z);
        }

        /*public Vector2 WorldToScreen(Vector2 worldPosition)
        {
            worldPosition.y *= -1f;
            Vector2 screenPosition = Microsoft.Xna.Framework.Vector2.Transform(worldPosition, GetViewMatrix());
            return screenPosition;
        }

        public Vector2 ScreenToWorld(Vector2 screenPosition)
        {
            Vector2 worldPosition = Microsoft.Xna.Framework.Vector2.Transform(screenPosition, Microsoft.Xna.Framework.Matrix.Invert(GetViewMatrix()));
            worldPosition.y *= -1f;
            return worldPosition;
        }*/
    }
}
